/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-10-20 10:18:52
 * @version $Id$
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    factory(exports);

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports);
  } else {
    // Browser globals
    if (!root._s) {
      root._s = {};
    }
    factory(root);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, undefined){
  'use strict';

  function moduleInit($, conf, log, utils){

    var urlConf = conf._conf;       //存储配置信息
    var threadId = urlConf.urlQuery.thread_id;

    var pubsub = utils.pubSub()||{};
    var callback = {};
    var callbackFuc = utils.callbackFuc;

    /*
      文本输入框
    */
    var msgInuptDom = $('.jsSendInput');

    /*
      添加实时监控文本框输入事件
    */
    (
      function(){
        var sendMsgBtnWidth = 100/750;
        var htmlFontSize = parseFloat($('html').css('fontSize'));

        var sentBtnDom = $('.jsSendBtn');

        msgInuptDom.bind('input', function(event) {
          /* Act on the event */
          var size = sendMsgBtnWidth*htmlFontSize;
          if ($(this).val()) {
            if (sentBtnDom.hasClass('s-hide')) {
              $(this).css({
                width : ($(this).width()-size) / htmlFontSize + 'rem'
              });

              sentBtnDom.removeClass('s-hide');
              sentBtnDom.css({
                width: sendMsgBtnWidth + 'rem'
              });
            }
          }else{
            $(this).css({
              width : ($(this).width()+size) / htmlFontSize + 'rem'
            });

            sentBtnDom.addClass('s-hide');
          }

        });
      }
        
    )();

    /*
      添加监控文件类型INPUT的change事件
        选择图片后上传图片，然后发送消息，渲染视图
    */
    (
      function(){

        var imgInuptDom = $('#jsImgInput');

        imgInuptDom.on('change', function(event) {
          /* Act on the event */

          event.preventDefault();

          if (!'FormData' in window) {
            alert('您的浏览器暂不支持图片上传，请更换浏览器！');

            return false;
          }

          var imgForm = new FormData();

          imgForm.append('imageFile',this.files[0]);
          /*

            触发上传图片事件
          */
          pubsub.fireEvent('upload',imgForm);

          this.value = '';

        }, false);
      }
        
    )();

    /*
      快捷回复跳转和发送信息按钮事件
    */
    (function(){
      $('.jsSendMsg').on('click', function(event) {
        
        /*
          事件委托
            根据HTML data-event属性判断哪个节点触发事件
            值：
              msg     ---   发送信息
              quick     ---   快捷回复
        */

        /* Act on the event */
        var target = $(event.target);
        var eventTarget = $(event.target).data('event');

        switch(eventTarget){
          case 'msg':
            event.preventDefault();

            /*
              触发上传文字消息事件--- sendMsg
            */

            pubsub.fireEvent('sendMsg', msgInuptDom.val());

          break;
          case 'quick':

            /*
              通知主程序执行快捷回复相关脚本
            */

            pubsub.fireEvent('quickreply',{code: 0 ,action: 'quick', threadId: threadId});

            /*
              
              跳转到快捷回复页面
                导航栏文字更改为---快捷回复列表
                获取快捷回复数据
                渲染视图
                添加事件
                  快捷回复语选中
                  使用事件
                  window回退事件
            */
          break;
        }

      });
    })();

    /*
      注册图片上传事件处理器
    */
    pubsub.addEvent('upload',function(data){
      log._log('图片上传了！');
      log._log(data);

      imgAjax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.upload,
        type: 'POST',
        data: data,
        success: function(data){
          log._log(data);

          if (data.code === 0) {

            pubsub.fireEvent('imgMsg',data.path);
            
          }else{
            pubsub.fireEvent('error',data);
          }
        },
        error: function(error){
          pubsub.fireEvent('error',{msg: error});
          log._log(error);
        }
      });
    });
    /*
      注册发送图片消息事件处理器
    */
    pubsub.addEvent('imgMsg',function(data){
      log._log('发送图片消息了！');
      log._log(data);

      var httpData = {
        type: 2,
        content: data,
        thread_id: threadId
      };

      pubsub.fireEvent('sendMsg',httpData);
    });
    /*
      注册文本消息上传事件处理器
    */
    pubsub.addEvent('sendMsg',function(data){
      log._log('消息上传了！');
      log._log(data);
      var httpData = data;

      if (typeof data !== 'object') {
        httpData = {
          type: 1,
          content: data,
          thread_id: threadId
        };

      }

      sendMsg(httpData);

    });
    /*
      错误事件处理器
    */
    pubsub.addEvent('error',function(data){
      log._log('发生错误了！');
      log._log(data);
    });

    /*
      弹框事件
    */
    pubsub.addEvent('alert',function(data){
      $('#fail').removeClass('s-hide');
      $('.js-warn-content').html(data.msg);
      addCloseEvent('.js-fail');
      log._log(data.msg);
    });
    /*
      添加弹框关闭按钮事件
    */
    function addCloseEvent(selector){
      $(selector).unbind('click').bind('click', function(event) {
        /* Act on the event */
        $($(this).data('target')).addClass('s-hide');

        $(selector).unbind('click');
      });
    }
    /*
      H5图片上传
    */
    function imgAjax(options){

      var oReq = new XMLHttpRequest();
      oReq.open(options.type||'', options.url||'');
      oReq.send(options.data||'');

      oReq.onload = function(data){
        log._log(this);
        if (this.readyState===4 && this.status===200) {
          log._log(data);
          if (typeof options.success === 'function') {
            options.success(JSON.parse(data.target.response));
          }
        }else{
          if (typeof options.error === 'function') {
            options.error(data.target.response);
          }
        }
      };
    }
    /*
      发送消息请求
    */
    function sendMsg(data){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.sendToUser,
        type: 'POST',
        dataType: 'json',
        data: data,
      })
      .done(function(data) {
        if (data.code === 0 ) {

          msgInuptDom.val('');
          msgInuptDom.trigger('input');


          if (data.data.type === '1') {
            data.data.msg = utils.setUrl(data.data.msg);
          }else{
            data.data.msg = urlConf.root + data.data.msg;
            data.data.thumb = data.data.msg.replace('uploads/kf/','uploads/kf/');
          }
          
          pubsub.fireEvent('success',[data.data]);
        }else{
          pubsub.fireEvent('fail',data);
        }
        
      })
      .error(function(error) {

        pubsub.fireEvent('fail',error);
      })
      .always(function() {
        log._log("complete");
      });
    }

    /*
      初始化-注册监听成功或者失败事件

    */

    function init(identifier, callbacks){
      
      callback[identifier] = [callbacks];

      pubsub.addEvent(identifier, function(data){
        callbackFuc(callback[identifier],data);
      });
     
    }

    return {
      receiver: init //接收通知
    };
  }


  exports.inputModule = moduleInit;

});